package yesjava;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MyDbUtil {
    private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    static {
        try {
            Properties dbpro = new Properties();
            dbpro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
            driver = dbpro.getProperty("db.driver");
            Class.forName(driver);
            url = dbpro.getProperty("db.url");
            user = dbpro.getProperty("db.user");
            password = dbpro.getProperty("db.password");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        Connection connection = threadLocal.get();// 第一次调用的时候，返回是null
        if(connection==null){
            try {
                connection = DriverManager.getConnection(url, user, password);
                threadLocal.set(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    public static void closeConnection() {
        Connection connection = threadLocal.get();
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        threadLocal.set(null);
    }
}
